/*=========================================================================

       wintime.cpp  -  Copyright (C) 1993-2005 by Don Cross

       Win32 version of ChessTime.  This function returns a
       time value expressed in hundredths of a second.
       The most important use of this function is to enable
       a timed search to know when to stop.

=========================================================================*/

#include <windows.h>

#include "chess.h"

INT32 ChessTime()
{
    static bool firstTime = true;
    static LARGE_INTEGER startTime;
    static LARGE_INTEGER performanceFrequency;

    LARGE_INTEGER pc;
    if (!QueryPerformanceCounter (&pc)) {
        ChessFatal ("Failure in QueryPerformanceCounter()");
    }

    if (firstTime) {
        startTime = pc;
        firstTime = false;

        if (!QueryPerformanceFrequency (&performanceFrequency)) {
            ChessFatal ("Failure in QueryPerformanceFrequency");
        }

        if (performanceFrequency.QuadPart <= 1000) {
            ChessFatal ("QueryPerformanceFrequency returned a value that is too small!");
        }

        performanceFrequency.QuadPart /= 100;       // instead of counts per second, we want counts per centisecond!

        return 0;
    } else {
        // WARNING:  This code can go 248.5513 days before wraping around the signed 32-bit integer.
        // That should be good enough for most uses, but it could cause problems some day.
        // If so, I will need to redesign ChessTime() to return a 64-bit integer.

        __int64 diff = pc.QuadPart - startTime.QuadPart;
        diff /= performanceFrequency.QuadPart;
        return (INT32) diff;
	}
}
